import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tag } from './entities/tag.entity';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(Tag)
    private tagRepository: Repository<Tag>,
  ) {}

  async create(createTagDto: CreateTagDto) {
    const existingTag = await this.tagRepository.findOne({
      where: { name: createTagDto.name },
    });

    if (existingTag) {
      throw new ConflictException('标签名已存在');
    }

    const tag = this.tagRepository.create(createTagDto);
    return await this.tagRepository.save(tag);
  }

  async findAll() {
    return await this.tagRepository.find();
  }

  async findByIds(ids: number[]) {
    return await this.tagRepository.findByIds(ids);
  }

  async remove(id: number) {
    const tag = await this.tagRepository.findOne({
      where: { id },
      relations: ['contents'],
    });
    
    if (tag && tag.contents && tag.contents.length > 0) {
      throw new ConflictException('该标签已被内容使用，无法删除');
    }

    return await this.tagRepository.delete(id);
  }

  async update(id: number, updateTagDto: UpdateTagDto) {
    const existingTag = await this.tagRepository.findOne({
      where: { id }
    });

    if (!existingTag) {
      throw new NotFoundException(`ID为 ${id} 的标签不存在`);
    }

    // 检查新名称是否与其他标签重复
    const duplicateTag = await this.tagRepository.findOne({
      where: { name: updateTagDto.name }
    });

    if (duplicateTag && duplicateTag.id !== id) {
      throw new ConflictException('标签名已存在');
    }

    existingTag.name = updateTagDto.name;
    return await this.tagRepository.save(existingTag);
  }
}